package com.example.synccenter.identitysource.processor;

import com.example.synccenter.entity.UserSyncRecordEntity;
import com.example.synccenter.service.UserSyncRecordService;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.UUID;

/**
 * 默认身份源用户后处理器，实现用户数据的同步后处理逻辑。
 */
@Slf4j
@Component
public class DefaultIdentitySourceUserPostProcessor extends AbstractIdentitySourcePostProcessor {
    @Autowired
    private UserSyncRecordService userSyncRecordService;

    /**
     * 构造方法，指定处理器名称
     */
    public DefaultIdentitySourceUserPostProcessor() {
        super("用户后处理器");
    }

    /**
     * 实现用户数据的具体处理逻辑
     * @param data 用户数据
     * @param context 同步上下文
     */
    @Override
    protected void doProcess(Map<String, Object> data, Map<String, Object> context) {
        // 从上下文中获取必要信息
        String sourceType = (String) context.get("sourceType");
        String sourceUserId = StringUtil.isEmpty((String) context.get("sourceUserId")) ? "source-user-id" : (String) context.get("sourceUserId");
        String localUserId = StringUtil.isEmpty((String) context.get("localUserId")) ? "local-user-id" : (String) context.get("localUserId");
        
        int userCount = (Integer) data.getOrDefault("users", 0);
        
        log.info("处理{}身份源用户数据: {}条", sourceType, userCount);

        try {
            // 写入同步记录
            UserSyncRecordEntity record = new UserSyncRecordEntity();
            record.setId(UUID.randomUUID().toString());
            record.setTaskId((String) context.get("taskId"));
            record.setSourceUserId(sourceUserId);
            record.setLocalUserId(localUserId);
            record.setOperation("同步");
            record.setStatus("成功");
            record.setErrorMessage(null);
            userSyncRecordService.save(record);
            log.info("{}身份源用户同步记录保存成功: {}", sourceType, sourceUserId);
        } catch (Exception e) {
            log.error("{}身份源用户同步记录保存失败: {}", sourceType, e.getMessage(), e);
            throw e;
        }
    }
} 